/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Canadian Weather.
 *
 * The Initial Developer of the Original Code is
 *   George Bradt.
 *
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   George Bradt.
 *
 * Credits:
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var CanWeatherRadar = {
    imageDivList: [],
    imageList: [],
    frameCount: 0,
    nextFrame: 0,
    previousFrame: 0,
    stationCode: '',
    srcBase: 'http://www.weatheroffice.gc.ca/radar/image.php?base=',
    srcOverlay: {
        combined: '',
        defaultCities: '&overlays[]=/radar/images/layers/default_cities/#sc_towns.gif',
        moreCities: '&overlays[]=/radar/images/layers/additional_cities/#sc_towns.gif',
        roads: '&overlays[]=/radar/images/layers/roads/#SC_roads.gif',
        roadNumbers: '&overlays[]=/radar/images/layers/road_labels/#sc_labs.gif',
        rivers: '&overlays[]=/radar/images/layers/rivers/#sc_rivers.gif',
        radarCircles: '&overlays[]=/radar/images/layers/radar_circle/radar_circle.gif'
    }
};

// Handle user-defined event emitted from add-on code after site data is retrieved and parsed.
// Initialize panel elements.
self.port.on('show', function(aImageList, aImageDateList, aRadarOptions) {
    if ( CanWeatherRadar.stationCode != aRadarOptions.stationCode ) {
        CanWeatherRadar.stationCode = aRadarOptions.stationCode;
        var stationCodeLowerCase = CanWeatherRadar.stationCode.toLowerCase();
        
        // Header.
        var text = aRadarOptions.stationName + ' (' + CanWeatherRadar.stationCode + ')'; 
        updateNode(document.getElementById('canw-name'), document.createTextNode(text));
            
        if ( CanWeatherRadar.srcOverlay.combined == '' ) {
            // First time this session. Build default overlay.
            CanWeatherRadar.srcOverlay.combined =
                    ( CanWeatherRadar.srcOverlay.roads.replace(/#SC/, CanWeatherRadar.stationCode) +
                      CanWeatherRadar.srcOverlay.radarCircles +
                      CanWeatherRadar.srcOverlay.defaultCities ).replace(/#sc/, stationCodeLowerCase);
        }
        else {
            CanWeatherRadar.srcOverlay.combined =
                    CanWeatherRadar.srcOverlay.combined.replace(/\/[A-Z]{3}_/, '/' + CanWeatherRadar.stationCode + '_').replace(/\/[a-z]{3}_/g, '/' + stationCodeLowerCase + '_');    
        }
    }
    
    CanWeatherRadar.frameCount = aImageList.length;
    var image, imageDate;
    
    for ( let i = 0; i < CanWeatherRadar.frameCount; i++ ) {
        image = document.getElementById('canw-image' + i);
        image.setAttribute('src', CanWeatherRadar.srcBase + aImageList[i] + CanWeatherRadar.srcOverlay.combined);
        
        imageDate = document.getElementById('canw-imageDate' + i);
        updateNode(imageDate, document.createTextNode(aImageDateList[i]));
    }

    if  ( CanWeatherRadar.imageDivList.length == 0 ) {
        for ( let i = 0; i < CanWeatherRadar.frameCount; i++ ) {
            CanWeatherRadar.imageDivList.push(document.getElementById('canw-wrapper' + i));
        }
    }
    
    CanWeatherRadar.imageList = aImageList;
        
    function updateNode(aElement, aContent) {
        // Shallow clone will not copy the content of the element.
        newElement = aElement.cloneNode(false);

        // Insert the cloned element before the original.
        aElement.parentNode.insertBefore(newElement, aElement);

        // Remove the original element.
        aElement.parentNode.removeChild(aElement);

        // Append new content.
        newElement.appendChild(aContent);
    }
});

// Add event listener to our Animate button.
document.getElementById('canw-buttonAnimate').addEventListener('click', function(aEvent) {
    CanWeatherRadar.nextFrame = CanWeatherRadar.frameCount;
    animate();
    
    function animate() {
        --CanWeatherRadar.nextFrame;
        CanWeatherRadar.previousFrame = ( CanWeatherRadar.nextFrame == CanWeatherRadar.frameCount - 1 ) ?
                0 : CanWeatherRadar.nextFrame + 1;
        
        if ( CanWeatherRadar.nextFrame >= 0 ) {
            CanWeatherRadar.imageDivList[CanWeatherRadar.nextFrame].style.zIndex = 1;
            CanWeatherRadar.imageDivList[CanWeatherRadar.previousFrame].style.zIndex = 0;
            window.setTimeout(function() { animate(); }, 1000);
        }
    }
}, true);

// Add event listener to our Reload button.
document.getElementById('canw-buttonReload').addEventListener('click', function(aEvent) {
    var stationCodeLowerCase = CanWeatherRadar.stationCode.toLowerCase();
    
    var defaultCities = ( document.getElementById('canw-cities').checked ) ?
            CanWeatherRadar.srcOverlay.defaultCities : '';
    var moreCities = ( document.getElementById('canw-moreCities').checked ) ?
            CanWeatherRadar.srcOverlay.moreCities : '';
    var roads = ( document.getElementById('canw-roads').checked ) ?
            CanWeatherRadar.srcOverlay.roads.replace(/#SC/, CanWeatherRadar.stationCode) : '';
    var roadNumbers = ( document.getElementById('canw-roadNumbers').checked ) ?
            CanWeatherRadar.srcOverlay.roadNumbers : '';
    var rivers = ( document.getElementById('canw-rivers').checked ) ?
            CanWeatherRadar.srcOverlay.rivers : '';
    var radarCircles = ( document.getElementById('canw-radarCircles').checked ) ?
            CanWeatherRadar.srcOverlay.radarCircles : '';
    CanWeatherRadar.srcOverlay.combined =
            ( rivers + roads + radarCircles + roadNumbers + moreCities + defaultCities ).replace(/#sc/g, stationCodeLowerCase);
            
    for ( let i = 0; i < CanWeatherRadar.frameCount; i++ ) {
        image = document.getElementById('canw-image' + i);
        image.setAttribute('src', CanWeatherRadar.srcBase + CanWeatherRadar.imageList[i] + CanWeatherRadar.srcOverlay.combined);
    }
}, true);

// Add event listener to our Ok button.
document.getElementById('canw-buttonOk').addEventListener('click', function(aEvent) {
    self.port.emit('ok-click');
    aEvent.preventDefault();
}, true);
